<template>
    <div class="patient-management">
        <!-- 搜索栏 -->
        <div class="search-bar">
            <el-input v-model="searchQuery" placeholder="请输入医生名称" clearable @clear="handleSearch"
                @keyup.enter="handleSearch">
                <template #append>
                    <el-button :icon="Search" @click="handleSearch" />
                </template>
            </el-input>
            <el-button type="primary" :icon="Plus" @click="handleAddData">新增医生</el-button>
        </div>

        <!-- Data列表 -->
        <el-table :data="filteredDatas" stripe style="width: 100%" @row-click="handleRowClick">
            <el-table-column v-for="column in columns" :key="column.prop" :prop="column.prop" :label="column.label"
                :sortable="column.sortable" />
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button type="link" :icon="Edit" @click.stop="handleEdit(scope.row)">编辑</el-button>
                    <el-button type="link" :icon="Delete" @click.stop="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="totalDatas"
                layout="total, sizes, prev, pager, next, jumper" @current-change="handlePageChange" />
        </div>

        <!-- Data详情抽屉 -->
        <el-drawer v-model="drawerVisible" title="医生详情" size="40%">
            <div v-if="selectedData">
                <h3>{{ selectedData.name }} 的详细信息</h3>
                <el-descriptions :column="1" border>
                    <el-descriptions-item label="名称">{{ selectedData.name }}</el-descriptions-item>
                    <el-descriptions-item label="手机号码">{{ selectedData.contactPhone }}</el-descriptions-item>
                    <el-descriptions-item label="职称">{{ selectedData.jobTitle.name }}</el-descriptions-item>
                    <el-descriptions-item label="专业">{{ selectedData.specialty.name }}</el-descriptions-item>
                    <el-descriptions-item label="是否在职">{{ selectedData.isActive }}</el-descriptions-item>
                    <el-descriptions-item label="所在科室">{{ selectedData.department.name }}</el-descriptions-item>
                </el-descriptions>
            </div>
        </el-drawer>

        <!-- 新增/编辑Data对话框 -->
        <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑医生' : '新增医生'">
            <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
                <el-form-item label="名称" prop="name">
                    <el-input v-model="form.name" />
                </el-form-item>
                <el-form-item label="手机号码" prop="contactPhone">
                    <el-input v-model="form.contactPhone" />
                </el-form-item>
                <el-form-item label="职称" prop="jobTitleID" placeholder="请选择职称" @click="onClickJobTitles">
                    <el-select v-model="form.jobTitleID">
                        <el-option v-for="jobTitle in jobTitles" :key="jobTitle.id" :label="jobTitle.name"
                            :value="jobTitle.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="专业" prop="specialtyID" placeholder="请选择专业" @click="onClickSpecialtys">
                    <el-select v-model="form.specialtyID">
                        <el-option v-for="specialty in specialtys" :key="specialty.id" :label="specialty.name"
                            :value="specialty.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="所在科室" prop="departmentID">
                    <el-select v-model="form.departmentID" placeholder="请选择科室" @click="onClickDepartments">
                        <el-option v-for="department in departments" :key="department.id" :label="department.name"
                            :value="department.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="是否在职" prop="isActive">
                    <el-switch v-model="form.isActive" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSubmit">确认</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue'
import { Search, Plus, Edit, Delete } from '@element-plus/icons-vue'
import { GetDoctor, PostDoctor, PutDoctor, DeleteDoctor } from '@/api/DoctorsService'
import { GetJobTitle } from '@/api/JobTitleService'
import { useI18n } from 'vue-i18n'
import { GetSpecialty } from '@/api/SpecialtyService'
import { GetDepartments } from '@/api/DepartmentService'
const { t } = useI18n()

const columns = [
    { prop: 'name', label: '姓名', sortable: true },
    { prop: 'userInfo.contactPhone', label: '姓名', sortable: true },
    { prop: 'jobTitle.name', label: '职业' },
    { prop: 'specialty.name', label: '专业' },
    { prop: 'department.name', label: '所在科室' },
    { prop: 'static', label: '状态', sortable: true }
]

const form = ref<any>({
    id: 0,
    name: "",
    contactPhone: null,
    jobTitleID: null,
    specialtyID: null,
    departmentID: null,
    static: ''
})

// 表单验证规则
const rules = ref({
    name: [
        { required: true, message: t('cannotBlank', { field: t('name') }), trigger: 'blur' },
        { min: 2, max: 20, message: '名称长度应为 2 到 20 个字符', trigger: 'blur' }
    ],

    contactPhone: [
        { required: true, message: t('cannotBlank', { field: t('contactPhone') }), trigger: 'blur' },
        // { min: 6, max: 15, message: t('contactPhone') + "长度应为 6 到 15 个字符", trigger: 'blur' }
    ],
    jobTitleID: [
        { required: true, message: t('cannotBlank', { field: t('jobTitle') }), trigger: 'blur' },
        // { min: 2, max: 20, message: '医生姓名长度应为 2 到 20 个字符', trigger: 'blur' }
    ],

    specialtyID: [
        { required: true, message: t('cannotBlank', { field: t('specialty') }), trigger: 'blur' },
        // { min: 2, max: 20, message: '医生姓名长度应为 2 到 20 个字符', trigger: 'blur' }
    ],
    departmentID: [
        { required: true, message: t('cannotBlank', { field: t('department') }), trigger: 'blur' },
        // { min: 10, max: 1000, message: '治疗方案长度应为 10 到 1000 个字符', trigger: 'blur' }
    ]
})

const datas = ref<any>([])
onMounted(async () => {
    datas.value = await GetDoctor()
})

// 搜索功能
const searchQuery = ref('')
const filteredDatas = computed(() => {
    return datas.value.filter(data =>
        data.name.includes(searchQuery.value)
        //|| data.idNumber.includes(searchQuery.value)
    )
})

// 分页功能
const currentPage = ref(1)
const pageSize = ref(10)
const totalDatas = computed(() => filteredDatas.value.length)

// 医生详情
const drawerVisible = ref(false)
const selectedData = ref<any>(null)

// 新增/编辑医生
const dialogVisible = ref(false)
const isEdit = ref(false)

// 方法
const handleSearch = () => {
    currentPage.value = 1
}

const handleRowClick = (data) => {
    selectedData.value = data
    drawerVisible.value = true
}

const handleAddData = () => {
    form.value = {
        id: 0,
        name: "",
        contactPhone: null,
        jobTitleID: null,
        specialtyID: null,
        departmentID: null,
        isActive: true
    }
    isEdit.value = false
    dialogVisible.value = true
}

const handleEdit = (data) => {
    // form.value = { ...patient }
    // const deleteProp = ['appointments', 'department', 'medicalRecords']
    // deleteProp.forEach(property => {
    //     delete form.value[property]
    // })
    form.value = data
    isEdit.value = true
    dialogVisible.value = true
}

const handleDelete = (data) => {
    datas.value = datas.value.filter(p => p.id !== data.id)
    DeleteDoctor(data.id)
}

const formRef = ref<any>(null)

const handleSubmit = () => {
    formRef.value.validate((valid) => {
        if (valid) {
            if (isEdit.value) {
                const index = datas.value.findIndex(p => p.id === form.value.id)
                datas.value[index] = { ...form.value }
                // PatchPatientApi(form.value.id, form.value)
                PutDoctor(form.value.id, form.value)
                console.log('编辑医生:', form.value)
            } else {
                datas.value.push({ ...form.value, id: datas.value.length + 1 })
                PostDoctor(form.value)
                console.log('新增医生:', form.value)
            }
            dialogVisible.value = false
        }
        else {
            console.log("表单验证失败");
        }
    })
}

const handlePageChange = (page) => {
    currentPage.value = page
}
const jobTitles = ref<any>()
const onClickJobTitles = async () => {
    jobTitles.value = await GetJobTitle()
    console.log(jobTitles)
}
const specialtys = ref<any>()
const onClickSpecialtys = async () => {
    specialtys.value = await GetSpecialty()
}
const departments = ref<any>()
const onClickDepartments = async () => {
    departments.value = await GetDepartments()
}
</script>

<style scoped>
.patient-management {
    padding: 20px;
}

.search-bar {
    display: flex;
    gap: 10px;
    margin-bottom: 20px;
}

.pagination {
    margin-top: 20px;
    text-align: right;
}

.el-button--link {
    text-decoration: none;
}
</style>